<template>
    <!-- pages/apartment_connect/apartment_connect.wxml -->
    <view class="container">
        <van-toast id="van-toast" />
        <view class="title">蓝牙设备列表</view>
        <view class="list">
            <block v-for="(item, index) in devices" :key="index">
                <view class="item" @tap="connectDevice" :data-device="item">
                    <view class="name">{{ item.name }}</view>
                    <view class="rssi">信号强度：{{ item.RSSI }}</view>
                </view>
            </block>
        </view>
    </view>
</template>

<script>
	import vanToast from '../../wxcomponents/vant/toast/index';
export default {
    data() {
        return {
            devices: []
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        uni.openBluetoothAdapter({
            success: (res) => {
                console.log('第一步，蓝牙适配器初始化完成', res);
                // 开始搜索附近蓝牙
                this.startBluetoothDevicesDiscovery();
            },
            // 如果失败显示提示信息
            fail: (res) => {
                Toast.fail('请开启手机蓝牙');
                // 自动返回上一个页面
                setTimeout(
                    () =>
                        uni.navigateBack({
                            delta: 1
                        }),
                    1500
                );
            }
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        // 第二步 开始搜索附近的蓝牙设备
        startBluetoothDevicesDiscovery() {
            uni.startBluetoothDevicesDiscovery({
                allowDuplicatesKey: false,
                success: (res) => {
                    console.log('开始搜索附近的蓝牙设备', res);
                    this.onBluetoothDeviceFound();
                }
            });
        },

        // 第三步 监听发现附近的蓝牙设备
        onBluetoothDeviceFound() {
            uni.onBluetoothDeviceFound((res) => {
                res.devices.forEach((device) => {
                    if (!device.name && !device.localName) {
                        return;
                    }
                    console.log('发现的蓝牙设备', device);
                    this.devices.push(device);
                    this.setData({
                        devices: this.devices
                    });
                });
            });
        },

        // 第四步、 建立连接
        connectDevice: function (e) {
            const device = e.currentTarget.dataset.device;
            uni.createBLEConnection({
                deviceId: device.deviceId,
                success: (res) => {
                    console.log('createBLEConnection success', res);
                    uni.showToast({
                        title: '蓝牙连接成功',
                        icon: 'none'
                    });
                    this.stopBluetoothDevicesDiscovery();
                    uni.navigateTo({
                        url: '/pages/main/main?deviceId=' + device.deviceId
                    });
                },
                fail: (res) => {
                    uni.showToast({
                        title: '蓝牙连接失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 第五步、 停止搜索
        stopBluetoothDevicesDiscovery() {
            uni.stopBluetoothDevicesDiscovery({
                success: function (res) {
                    console.log('停止搜索成功');
                },
                fail: function (res) {
                    console.log('停止搜索失败');
                }
            });
        }
    }
};
</script>
<style>
/* pages/apartment_connect/apartment_connect.wxss */
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

.title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
}

.list {
    width: 100%;
}

.item {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #eee;
}

.name {
    font-size: 16px;
    font-weight: bold;
}

.rssi {
    font-size: 14px;
    color: #999;
}
</style>
